import axios from "axios";
import { useTokenStore } from "@/stores/token";
import { ElMessage } from "element-plus";
import router from "@/router";
import { convertMinioUrl } from "@/utils/convertMinioUrl";

const baseURL = "/api";
const instance = axios.create({ baseURL });

// 递归转换数据中所有字符串的 MinIO 链接
const processData = (data) => {
  if (typeof data === "string") {
    return convertMinioUrl(data);
  } else if (Array.isArray(data)) {
    return data.map(processData);
  } else if (typeof data === "object" && data !== null) {
    for (const key in data) {
      data[key] = processData(data[key]);
    }
    return data;
  }
  return data;
};

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const tokenStore = useTokenStore();
    if (tokenStore.token) {
      config.headers.Authorization = tokenStore.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code === 0) {
      // 成功时处理数据，转换 MinIO 链接
      res.data = processData(res.data);
      return res;
    } else if (res.code === 401) {
      ElMessage.error("登录过期，请重新登录");
      router.push("/login");
      return Promise.reject(res);
    } else {
      ElMessage.error(res.message || "未知错误");
      return Promise.reject(res);
    }
  },
  (error) => {
    ElMessage.error("请求失败");
    return Promise.reject(error);
  }
);

export default instance;
